import defaultSettings from '@/config/defaultSettings';
import store from '@/store';
/**
 * 解析传入的url
 * @param {string} url
 * @return {*} 返回url的路径和参数
 */
export function parseURL(url: string): any {
    const query = {};
    const path = url.split('?')[0];
    const queryStr = url.split('?')[1];
    const searchParams = new URLSearchParams(queryStr);
    for (const pair of searchParams.entries()) {
        query[pair[0]] = pair[1];
    }
    return { query, path };
}

/**
 * 防抖，固定时间内执行多次操作，只执行最后一次请求
 * @param fn 
 * @param wait 
 * @returns 
 */
export const debounce = (fn, wait) => {
    let timer;
    return function (...args) {
        if (timer) {clearTimeout(timer)}
        timer = setTimeout(() => {
            fn(...args);
        }, wait);
    };
};

/**
 * 深拷贝对象
 * @param {*} source 
 * @returns {*}
 */
export const deepClone = (source) => {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments');
    }
    const targetObj = source.constructor === Array ? [] : {};
    for (const keys in source) {
        if (Reflect.has(source, keys)) {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = source[keys].constructor === Array ? [] : {};
                targetObj[keys] = deepClone(source[keys]);
            } else {
                targetObj[keys] = source[keys];
            }
        }
    }
    return targetObj;
};

/**
 * 根据数组对象中某一个属性，进行去重获取唯一数组
 * @param arr 数组数据
 * @param field 数组中某一对象的属性，去重纯数组属性就是index
 * @returns 
 */
export const getUniqueArr = (arr, field) => {
    const res = new Map();
    return arr.filter((item) => {
        const attrItem = item[field];
        return !res.has(attrItem) && res.set(attrItem, 1);
    });
};

/**
 * 根据传入的平台名称，获取平台的IP
 * @param name 平台名称
 * @returns 
 */
export const getOtherPlatformIp = (name: string) => {
    const { protocol, hostname } = document.location;
    const { production, otherPlatformUrl } = defaultSettings;
    return production ? `${protocol}//${hostname}:${otherPlatformUrl[name].port}` : otherPlatformUrl[name].devTargetUrl;
};


export const hasPerm = (value: string) => {
    const d: any = deepClone(store.getters);//拷贝一份数据
    return d.authInfo.includes(value);
};

/**
 * 实现一个批量请求函数
 * 每当有一个请求返回，就留下一个空位，可以增加新的请求
 * 所有请求完成后，结果按照数组funcArray里面的顺序依次打出
 * @param {Promise[]} funcArray
 * @param {number} [limit=5] 要求最大并发数 limit
 * @returns Promise<any>
 */
export function multiRequest(funcArray: Array<any>, limit = 5) {
    let i = 0;
    const result: any = []; // 完成集合
    const executing: any = []; // 执行集合
    const queue = () => {
        if (i === funcArray.length) { // 判断是否全部执行完
            return Promise.all(executing);
        }
        const p = funcArray[i++]();
        result.push(p);
        const e: any = p.then(() => executing.splice(executing.indexOf(e), 1)); // 执行完从executing中剔除一个
        executing.push(e);

        if (executing.length >= limit) { // 判断executing中的长度是否大于等于限制数limit
            // 当 Promise.race 时会等到其中一个执行完才执行下一步
            return Promise.race(executing).then(() => queue(), (e) => Promise.reject(e));
        }
        return Promise.resolve().then(() => queue());
    };
    return queue().then(() => Promise.all(result)); // 全部执行完按顺序返回
}

export const isMobile = () => {
    return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
};

